package com.zzyl.nursing.service.impl;
import cn.hutool.core.date.DateUtil;
import com.zzyl.nursing.domain.Contract;

import com.alibaba.fastjson2.JSON;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住管理Service业务层处理
 *
 * @author syl
 * @date 2025-05-24
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 查询入住表
        CheckIn checkIn = checkInMapper.selectById(id);  //MP
// '[{"kinship":"0","name":"小张1","phone":"13555555555"},{"kinship":"0","name":"小张2","phone":"13444444444"}] '
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 查询老人
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();

        // 根据生日计算年龄
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 查询入住配置
        Long checkInId = checkIn.getId();
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<CheckInConfig>();
        queryWrapper.eq(CheckInConfig::getCheckInId,checkInId);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);


        // 查询合同
        LambdaQueryWrapper<Contract> queryWrapper1 = new LambdaQueryWrapper<Contract>();
        queryWrapper1.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(queryWrapper1);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;

    }

    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     *
     * @param dto 入住管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCheckIn(CheckInApplyDto dto) {
        // 入住信息DTO
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        // 入住合同DTO
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        // 老人家属
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        // 老人信息
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();


        //校验老人是否已入住  如果已入住直接抛异常BaseException
        // 根据老人身份证号和入住状态查询是否有此老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus,4);  //0=：禁用，1:启用,2=:请假,3=:退住中,4=入住中,5=已退住
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder!=null){
            throw new BaseException("该老人已入住");
        }

        //更新床位的状态  update bed set status=1 where id=?
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(1);  //床位状态: 未入住0, 已入住1 入住申请中2
        bedMapper.updateById(bed);  // MP提供的修改方法

        //新增或更新老人elder
        elder = saveOrUpdateElder(checkInElderDto,bed);

        //新增合同信息  合同号要求： HT+16位数字，例：HT202501011012590001
        saveContract(checkInContractDto,elder,checkInConfigDto);


        //新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckIn(elder,elderFamilyDtoList,checkInConfigDto);


        //新增入住配置
        saveCheckInConfig(checkInConfigDto,checkIn);


        return 1;
    }

    //新增入住配置
    private void saveCheckInConfig(CheckInConfigDto configDto,CheckIn checkIn ) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(configDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig); //MP的新增方法
    }

    //新增入住信息  老人家属信息存到remark字段中
    private CheckIn saveCheckIn(Elder elder, List<ElderFamilyDto> elderFamilyDtoList, CheckInConfigDto checkInConfigDto) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);  //状态 (0: 已入住, 1: 已退住)

        // 把集合转成json字符串
        String string = JSON.toJSONString(elderFamilyDtoList);
        checkIn.setRemark(string); //老人家属信息存到remark字段中
        // 根据json字符串获取集合
        // List<ElderFamilyDto> elderFamilyDtos = JSON.parseArray(string, ElderFamilyDto.class);

        checkInMapper.insert(checkIn); // MP的新增方法

        return checkIn;
    }

    //新增合同信息
    private void saveContract(CheckInContractDto contractDto,Elder elder,CheckInConfigDto checkInConfigDto) {
    //    合同号要求： HT+16位数字，例：HT202501011012590001
        Contract contract = new Contract();

        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());  // HT+16位数字，例：HT202501011012590001
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setSignDate(contractDto.getSignDate());

        contract.setStartDate(checkInConfigDto.getStartDate());  //开始时间
        contract.setEndDate(checkInConfigDto.getEndDate());   // 结束时间
        contract.setStatus(1);   //状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)


        //  解约信息 暂时不考虑
        // contract.setTerminationSubmitter("");
        // contract.setTerminationDate(LocalDateTime.now());
        // contract.setTerminationAgreementPath("");
        contract.setSortOrder(0);

        contractMapper.insert(contract);  //MP的新增方法


    }

    //新增或更新老人elder
    private Elder saveOrUpdateElder(CheckInElderDto elderDto,Bed bed) {
        boolean  isNew = false; //是否要新增老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder==null){
            isNew = true;
            // 新增
            elder = new Elder();
        }
        BeanUtils.copyProperties(elderDto,elder); //属性名和类型一致
        elder.setStatus(4);   ///0=：禁用，1:启用,2=:请假,3=:退住中,4=入住中,5=已退住
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());

        if(isNew){
            elderMapper.insert(elder);  //MP提供的新增方法 有自动填充的  createTime
        }else{
            elderMapper.updateById(elder);  //MP提供的新增方法 有自动填充的
        }

        return elder;

    }

    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

}
